package me.ywy.opengltest.view;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import me.ywy.opengltest.filter.CameraFilter;
import me.ywy.opengltest.filter.ScreenFilter;
import me.ywy.opengltest.utils.CameraHelper;

/**
 * Created by ywy on 2018-10-31.
 * Surface渲染器
 */
public class DouyinRenderer implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {

    private CameraHelper mCameraHelper;
    private SurfaceTexture mSurfaceTexture;
    private DouyinView mView;
    private float[] mtx = new float[16];
    private ScreenFilter mScreenFilter;
    private int[] mTextures;
    private CameraFilter mCameraFilter;

    public DouyinRenderer(DouyinView douyinView) {

        mView = douyinView;
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        //页面创建好了
        mCameraHelper = new CameraHelper(Camera.CameraInfo.CAMERA_FACING_BACK);
        mTextures = new int[1];
        GLES20.glGenTextures(mTextures.length , mTextures, 0);
        mSurfaceTexture = new SurfaceTexture(mTextures[0]);
        //设置回调
        mSurfaceTexture.setOnFrameAvailableListener(this);

        mCameraFilter = new CameraFilter(mView.getContext());
        mScreenFilter = new ScreenFilter(mView.getContext());
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        //画布变化的时候调用
        //开启预览
        mCameraHelper.startPreview(mSurfaceTexture);

        mCameraFilter.onReady(width , height);
        mScreenFilter.onReady(width , height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        //页面绘制的时候调用
        //告诉屏幕清理城什么颜色
        GLES20.glClearColor( 0,0,0,0);
        //执行
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        //更新纹理 然后才能使用openGL从类中获取数据
        mSurfaceTexture.updateTexImage();
        //获取变换矩阵
        mSurfaceTexture.getTransformMatrix(mtx);

        mCameraFilter.setMatrix(mtx);

        int id = mCameraFilter.onDrawFrame(mTextures[0]);


        mScreenFilter.onDrawFrame(id);


    }

    @Override
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        //有一个有效的新数据的时候回调
        mView.requestRender();
    }



    public void onSurfaceDestroyed() {
        mCameraHelper.stopPreview();
    }
}
